package com.iiiu.payment.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.iiiu.payment.domain.dto.LoginDTO;
import com.iiiu.payment.domain.dto.PageQueryDTO;
import com.iiiu.payment.domain.dto.RegisterDTO;
import com.iiiu.payment.domain.dto.UserDTO;
import com.iiiu.payment.domain.entity.User;
import com.iiiu.payment.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import com.iiiu.payment.common.Result;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.Map;

/**
 * 用户控制器
 */
@Tag(name = "用户管理", description = "用户相关API")
@RestController
@RequestMapping("/api/user")
@Validated

public class UserController {

    @Autowired
    private UserService userService;

    @Operation(summary = "用户注册", description = "注册新用户")
    @PostMapping("/register")
    public UserDTO register(@Valid @RequestBody RegisterDTO registerDTO) {
        UserDTO userDTO = userService.register(registerDTO);
        return userDTO;
    }

    @Operation(summary = "用户登录", description = "用户登录验证")
    @PostMapping("/login")
    public UserDTO login(@Valid @RequestBody LoginDTO loginDTO) {
        UserDTO login = userService.login(loginDTO);
        if (login == null) {
            return null;
        }
        StpUtil.login(login.getId());
        return login;
    }

    @Operation(summary = "根据ID查询用户", description = "根据用户ID查询用户信息")
    @GetMapping("/{id}")
    public UserDTO getUserById(
            @Parameter(description = "用户ID") @PathVariable @NotNull Long id) {
        UserDTO userDTO = userService.getUserById(id);
        return userDTO;
    }

    @Operation(summary = "根据用户名查询用户", description = "根据用户名查询用户信息")
    @GetMapping("/username/{username}")
    public UserDTO getUserByUsername(
            @Parameter(description = "用户名") @PathVariable @NotBlank String username) {
        UserDTO userDTO = userService.getUserByUsername(username);
        return userDTO;
    }

    @Operation(summary = "更新用户信息", description = "更新用户基本信息")
    @PutMapping("/{id}")
    public UserDTO updateUser(
            @Parameter(description = "用户ID") @PathVariable @NotNull Long id,
            @Valid @RequestBody UserDTO userDTO) {
        userDTO.setId(id);
        UserDTO updatedUser = userService.updateUser(userDTO);
        return updatedUser;
    }

    @Operation(summary = "删除用户", description = "软删除用户")
    @DeleteMapping("/{id}")
    public void deleteUser(
            @Parameter(description = "用户ID") @PathVariable @NotNull Long id) {
        boolean deleted = userService.deleteUser(id);
        if (!deleted) {
            throw new IllegalArgumentException("用户不存在或已被删除");
        }
    }

    @Operation(summary = "分页查询用户", description = "分页查询用户列表")
    @GetMapping
    public IPage<UserDTO> getUserPage(@Valid PageQueryDTO pageQueryDTO) {
        IPage<UserDTO> userPage = userService.getUserPage(pageQueryDTO);
        return userPage;
    }

    @Operation(summary = "检查用户名是否存在", description = "检查用户名是否已被使用")
    @GetMapping("/exists/{username}")
    public Map<String, Object> checkUsernameExists(
            @Parameter(description = "用户名") @PathVariable @NotBlank String username) {
        boolean exists = userService.existsByUsername(username);
        
        Map<String, Object> data = Map.of("exists", exists);
        return data;
    }

    @Operation(summary = "修改密码", description = "修改用户密码")
    @PutMapping("/{id}/password")
    public void changePassword(
            @Parameter(description = "用户ID") @PathVariable @NotNull Long id,
            @RequestBody Map<String, String> passwordData) {
        String oldPassword = passwordData.get("oldPassword");
        String newPassword = passwordData.get("newPassword");
        boolean success = userService.changePassword(id, oldPassword, newPassword);
        if (success) {
            return;
        } else {
            throw new IllegalArgumentException("旧密码错误");
        }
    }

    @Operation(summary = "用户登出", description = "用户登出，清除登录状态")
    @PostMapping("/logout")
    public void logout() {
        StpUtil.logout();
    }

    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的详细信息")
    @GetMapping("/current")
    public UserDTO getCurrentUser() {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 从Session中获取用户信息
        User user = (User) StpUtil.getSession().get("user");
        if (user != null) {
            // 如果Session中有用户信息，直接转换返回
            UserDTO userDTO = userService.getUserById(user.getId());
            return userDTO;
        } else {
            // 如果Session中没有，从数据库查询
            UserDTO userDTO = userService.getUserById(userId);
            return userDTO;
        }
    }
}